/**
 * 
 */
package ads.engenharia.dal;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import ads.engenharia.entity.Discipline;
import ads.engenharia.entity.Professor;

/**
 * @author Lanedraex
 *
 */
public class ProfessorCompetenceDAO {

	private String sql;
	private String tableName = "\"Professor_Competence\"";

	private EntityManager em = new EntityManager() {

		@Override
		public Object treatResultSet(ResultSet resultSet) throws SQLException {
			Professor professor = new Professor();

			professor.competence(searchProfessorCompetence(professor.id()));
			return professor;
		}
	};

	/**
	 * 
	 * @param professor
	 * @throws SQLException
	 */
	public void save(Professor professor) throws SQLException {

		sql = " insert into " + tableName + " ( discipline_id, professor_id ) ";

		for (Discipline discipline : professor.competence())
			em.executeQuery(sql, discipline.id(), professor.id());

	}

	/**
	 * 
	 * @param professor
	 * @throws SQLException
	 */
	public void update(Professor professor) throws SQLException {

		sql = " update " + tableName
				+ " set discipline_id = ? where professor_id = ?";

		for (Discipline discipline : professor.competence())
			em.executeQuery(sql, discipline.id(), professor.id());
	}

	/**
	 * 
	 * @param professor
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<Discipline> searchProfessorCompetence(Professor professor)
			throws SQLException {

		sql = " select distinct discipline_id from " + tableName
				+ " where professor_id = ? ";

		return (ArrayList<Discipline>) em.getResultList(sql, professor.id());
	}

	/**
	 * 
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<Discipline> searchProfessorCompetence(int id)
			throws SQLException {

		sql = " select distinct discipline_id from " + tableName
				+ " where professor_id = ? ";

		return (ArrayList<Discipline>) em.getResultList(sql, id);
	}

}
